package com.ruoyi.smart.mqtt.handler;

import com.ruoyi.smart.mqtt.MessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;

/**
 * 设备状态处理器
 * 处理设备上下线状态信息
 */
@Slf4j
@Component
public class DeviceStatusHandler implements MessageHandler {

    @Override
    public String getTopicFilter() {
        // 匹配设备状态主题，如: sch/gw001/status, sch/gw002/status
        return "sch/+/status";
    }

    @Override
    public void handleMessage(String topic, MqttMessage message) {
        String payload = new String(message.getPayload());
        log.info("处理设备状态更新: topic={}, status={}", topic, payload);

        try {
            String[] topics = topic.split("/");
            String deviceId = topics[1]; // 获取设备ID

            // 处理设备状态更新
            processDeviceStatus(deviceId, payload);

        } catch (Exception e) {
            log.error("处理设备状态失败: topic={}", topic, e);
            throw new RuntimeException("处理设备状态失败", e);
        }
    }

    private void processDeviceStatus(String deviceId, String status) {
        // 这里实现设备状态处理的业务逻辑
        log.debug("设备 {} 状态更新为: {}", deviceId, status);

        // 示例: 更新设备状态到数据库和Redis
        // deviceStatusService.updateStatus(deviceId, status);
    }
}
